<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AccountController
 *
 * @author bom
 */
class User_AccountController extends My_Controller_Action
{

	//put your code here
	public function init()
	{
		parent::init();
	}

	protected function generateCaptcha()
	{
		$imgDir = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'captcha' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR;
		$fontDir = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'captcha' . DIRECTORY_SEPARATOR . 'font' . DIRECTORY_SEPARATOR;
		$captcha = new Zend_Captcha_Image();
		$captcha->setTimeout('300')
				->setWordLen('6')
				->setHeight('60')
				->setWidth('145')
				//->setFontSize('20')
				//->setImgDir(APPLICATION_PATH . '/../public/captcha/images/')
				->setImgDir($imgDir)
				->setImgUrl($this->view->baseUrl() . '/public/captcha/images/')
				->setLineNoiseLevel(3)  // sets the line noise
				->setDotNoiseLevel(40)  // sets the dot nois
				->setExpiration(0)
				->setGcFreq(0)
				->setFont($fontDir . 'tahoma.ttf');
		$captcha->generate();
		$this->view->captcha = $captcha->render($this->view);
		$this->view->captchaID = $captcha->getId();
		// Dua chuoi Captcha vao session
		$captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captcha->getId());
		$captchaSession->word = $captcha->getWord();
	}

	protected function isCaptchaMatch()
	{
		$captchaID = $this->_request->captcha_id;
		$captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captchaID);
		$captchaIterator = $captchaSession->getIterator();
		$captchaWord = $captchaIterator['word'];

		if($this->_request->captcha == $captchaWord)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	public function registerAction()
	{
		$auth = Zend_Auth::getInstance();
		if($auth->hasIdentity())
		{
			$redirect_url = $this->getUrl(array("module" => "cms", "controller" => "index", "action" => "index"));
			$this->_redirect($redirect_url);
		}

		$this->view->rightModules('right');
		$this->view->errors = $this->_errorMessenger->getMessages();
		$this->_errorMessenger->clearMessages();
		$this->generateCaptcha();
		$mCategory = $this->loadModel('admin_cms', 'Category');
		$this->view->categories = $mCategory->fetchAll($mCategory->select());
		$this->view->postData = $this->postData->data;
	}

	public function registerpostAction()
	{
		try
		{
			$auth = Zend_Auth::getInstance();
			if($auth->hasIdentity())
			{
				$redirect_url = $this->getUrl(array("module" => "cms", "controller" => "index", "action" => "index"));
				$this->_redirect($redirect_url);
			}

			$model = $this->loadModel('admin_user', 'Account');

			$this->postData->data = $this->_request->getParams();

			if(!$this->_request->getParam("username"))
			{
				$this->_errorMessenger->addMessage("Nhập tên đăng nhập");
			}
			else
			{
				if($model->isUsernameUsed($this->_request->getParam("username")))
				{
					$this->_errorMessenger->addMessage("Tên đăng nhập đã được sử dụng!");
				}
			}
			if(!$this->_request->getParam("password"))
			{
				$this->_errorMessenger->addMessage("Nhập mật khẩu");
			}
			if(!$this->_request->getParam("password2"))
			{
				$this->_errorMessenger->addMessage("Xác nhận mật khẩu");
			}
			if($this->_request->getParam("password") != $this->_request->getParam("password2"))
			{
				$this->_errorMessenger->addMessage("Xác nhận mật khẩu");
			}
			if(!$this->_request->getParam("email"))
			{
				$this->_errorMessenger->addMessage("Nhập email");
			}
			else
			{
				if($model->isEmailUsed($this->_request->getParam("email")))
				{
					$this->_errorMessenger->addMessage("Email đã được sử dụng!");
				}
			}
			if(!$this->isCaptchaMatch())
			{
				$this->_errorMessenger->addMessage($this->view->translate("Sai mã xác nhận !"));
			}
			if(count($this->_errorMessenger->getCurrentMessages()) > 0)
			{
				$this->postData->data = $this->_request->getParams();
				$redirect_url = $this->getUrl(array("module" => "user", "controller" => "account", "action" => "register"));
				$this->_redirect($redirect_url);
			}
			else
			{
				$newuser = $model->createrow();
				$newuser->username = $this->_request->getParam("username");
				$newuser->fullname = $this->_request->getParam("username");
				$newuser->password = md5($this->_request->getParam("password"));
				$newuser->email = $this->_request->getParam("email");
				$newuser->phone = $this->_request->getParam("phone");
				$newuser->interested_in = implode(",", $this->_request->getParam("interested_in"));
				$newuser->group_id = 2;
				$newuser->active = 0;
				$id = $newuser->save();

				// send mail
				$link = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
				$link .= $_SERVER["SERVER_NAME"] . $this->view->baseUrl("index.php/user/account/confirm/id/$id");
				
				$data = array(
					'subject' => "Chào mừng {$newuser->username} đến với HỘP MUA",
					'fmail' => 'info@hopmua.com',
					'fname' => 'admin',
					'tmail' => $newuser->email,
					'tname' => $newuser->username
				);
				$content = array("username" => $newuser->username, "link" => $link);
				$this->sendmail($data, '', 'confirm.html', $content);
			}
		}
		catch(Exception $ex)
		{
			echo $ex->getMessage();
		}
	}

	public function logoutAction()
	{
		$user = $this->auth->getIdentity();
		if($user->username != "facebooker")
		{
			$query = "delete from checkout_cart_item where user_id = $user->user_id";
			$tb = Zend_Db_Table::getDefaultAdapter();
			$tb->fetchAll($query);
		}

		$this->auth->clearIdentity();
		$session = new Zend_Session_Namespace('fb');
		$session->login = false;

		$redirect_url = "";
		$this->_redirect($redirect_url);
	}

	public function loginAction()
	{
		$this->view->rightModules('right');
		$this->view->postData = $this->postData->data;
		$this->view->errors = $this->_errorMessenger->getMessages();
		$this->_errorMessenger->clearMessages();
	}

	public function loginpostAction()
	{
		if($this->_request->isPost())
		{
			if($this->_request->getParam('submit'))
			{
				//4. Lay gia tri duoc gui qua tu FORM
				$uname = $this->_request->getParam('username');
				$paswd = $this->_request->getParam('password');
				$remember = isset($_POST['cbSavePassword']) && $_POST['cbSavePassword'];

				// check active
				$model = $this->loadModel("user", "Account");
				$user = $model->getUserByUsername($uname);
				if($user->active == 0)
				{
					$this->_errorMessenger->addMessage("Tài khoản chưa được kích hoạt");
					$this->postData->data = $this->_request->getParams();
					$this->_redirect("user/account/login");
				}
				
				if($uname == null)
				{
					$this->view->error = "Nhập tên đăng nhập";
					$this->_errorMessenger->addMessage($this->view->error);
				}
				else if($paswd == null)
				{
					$this->view->username = $uname;
					$this->view->error = "Nhập mật khẩu";
					$this->_errorMessenger->addMessage($this->view->error);
				}
				else
				{
					//1.Goi ket noi voi Zend Db
					$db = Zend_Registry::get('connectDB');
					//$db = Zend_Db::factory($dbOption['adapter'],$dbOption['params']);
					//2. Khoi tao Zend Autho
					$auth = Zend_Auth::getInstance();

					//3. Khai bao bang va 2 cot se su dung so sanh trong qua trinh login
					$authAdapter = new Zend_Auth_Adapter_DbTable($db);
					$authAdapter->setTableName('user_account')
							->setIdentityColumn('username')
							->setCredentialColumn('password');

					//5. Dua vao so sanh voi du lieu khai bao o muc 3
					$authAdapter->setIdentity($uname);
					//$authAdapter->setCredential($paswd);
					$authAdapter->setCredential(md5($paswd));
					//6. Kiem tra trang thai cua user neu status = 1 moi duoc login
					//$select = $authAdapter->getDbSelect();
					//$select->where('permission = 0');
					//7. Lay ket qua truy van
					$result = $auth->authenticate($authAdapter);
					$flag = false;

					if($result->isValid())
					{
						//8. Lay nhung du lieu can thiet trong bang users neu login thanh cong
						$user = $authAdapter->getResultRowObject(null, array('password'));

						//9. Luu  nhung du lieu cua member vao session
						$auth->getStorage()->write($user);

						//Luu thong tin ngay gio dang nhap
						/* $auth = Zend_Auth::getInstance();
						  $userTable = new Users();
						  $user = $userTable->fetchRow($userTable->select()->where('id=?', $auth->getIdentity()->id));
						  $user->login_time = date("y-m-d G:i:s");
						  $user->save(); */
						//login success
						//$redirect_url = $this->getUrl(array("module" => "cms", "controller" => "index", "action" => "index"));
						// remember me
						if($remember)
						{
							Zend_Session::RememberMe($seconds);
						}
						else
						{
							Zend_Session::ForgetMe();
						}

						//========= move cart session to cart database ========
						$mDeal = $this->loadModel('admin_cms', 'Deal');
						$mCart = $this->loadModel('checkout', 'CartItem');
						$cartSes = $this->loadModel('checkout', 'CartSession');
						$cartSes->moveToDatabase($mDeal, $mCart, $user);
						//======= end move cart session to cart database ======

						$session = new Zend_Session_Namespace('lastRequest');
						$link = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://" . $_SERVER["SERVER_NAME"] . $session->lastRequestUri;
						$this->_redirect($link);
					}
					else
					{
						$this->view->error = "Đăng nhập lại";
						$this->_errorMessenger->addMessage($this->view->error);
					}
				}
				$redirect_url = $this->getUrl(array("module" => "user", "controller" => "account", "action" => "login"));
				$this->postData->data = $this->_request->getParams();
				$this->_redirect($redirect_url);
			}
			else if($this->_request->getParam('cancel'))
			{
				$this->_redirect('/admin_user/index/index');
			}
		}
	}

	public function lostpasswordAction()
	{
		if(!$this->_errorMessenger->hasMessages() && !$this->_notifyMessenger->hasMessages())
		{
			// check login
			$auth = Zend_Auth::getInstance();
			if($auth->hasIdentity())
			{
				$redirect_url = $this->getUrl(array("module" => "cms", "controller" => "index", "action" => "index"));
				$this->_redirect($redirect_url);
			}

			$this->view->rightModules('right');
		}

		$this->view->errors = $this->_errorMessenger->getMessages();
		$this->_errorMessenger->clearMessages();

		$this->view->notifies = $this->_notifyMessenger->getMessages();
		$this->_notifyMessenger->clearMessages();
	}

	public function lostpasswordpostAction()
	{
		// check post method
		if(!$this->_request->isPost())
		{
			$this->_redirect("cms");
		}

		// get email input
		$email = $this->_request->getParam('email');

		// check input is email?
		$validator = new Zend_Validate_EmailAddress();
		if(!$validator->isValid($email))
		{
			$this->_errorMessenger->addMessage("Email không đúng");
			$this->_redirect("user/account/lostpassword");
		}

		// get user by email
		$userModel = $this->loadModel("user", "Account");
		$user = $userModel->getUserByEmail($email);

		// email is not exist
		if($user == null)
		{
			$this->_errorMessenger->addMessage("Email không tồn tại");
			$this->_redirect("user/account/lostpassword");
		}

		// request again
		$resettingModel = $this->loadModel("user", "Resetting");
		if($resettingModel->isRequested($user["user_id"]))
		{
			$resetting = $resettingModel->getResettingByUserId($user["user_id"]);
		}
		else
		{
			// create resetting
			$resetting = array();
			$resetting["user_id"] = $user["user_id"];
			$resetting["guid"] = uniqid();

			// add to db
			$resetting_id = $resettingModel->addResetting($resetting);
		}

		// create link
		$link = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
		$link .= $_SERVER["SERVER_NAME"] . $this->view->baseUrl("/index.php/user/account/reset?guid={$resetting['guid']}");

		// send mail
		$data = array(
			'subject' => "Thay đổi mật khẩu - HỢP MUA",
			'fmail' => 'info@hopmua.com',
			'fname' => 'admin',
			'tmail' => $user->email,
			'tname' => $user->username
		);
		$content = array("url" => $link);
		$this->sendmail($data, '', 'lostpassword.html', $content);

		$this->_notifyMessenger->addMessage("Gửi mail thành công");

		$this->_redirect("user/account/lostpassword");
	}

	public function indexAction()
	{
		$auth = Zend_Auth::getInstance();
		if($auth->hasIdentity())
		{
			$this->view->user = $auth->getIdentity();

			$this->view->errors = $this->_errorMessenger->getMessages();
			$this->_errorMessenger->clearMessages();

			$this->view->notifies = $this->_notifyMessenger->getMessages();
			$this->_notifyMessenger->clearMessages();
		}
		else
		{
			$redirect_url = $this->getUrl(array("module" => "user", "controller" => "account", "action" => "login"));
			$this->_redirect($redirect_url);
		}
	}

	public function resetAction()
	{
		// check message
		if(!$this->_errorMessenger->hasMessages() && !$this->_notifyMessenger->hasMessages())
		{
			// get guid
			$guid = $this->_request->getParam("guid");
			if($guid == null)
			{
				$redirect_url = $this->getUrl(array("module" => "cms", "controller" => "index", "action" => "index"));
				$this->_redirect($redirect_url);
			}

			// get resetting by guid
			$resettingModel = $this->loadModel("user", "Resetting");
			$resetting = $resettingModel->getResettingByGuid($guid);

			// guid is not exist
			if($resetting == null)
			{
				$redirect_url = $this->getUrl(array("module" => "cms", "controller" => "index", "action" => "index"));
				$this->_redirect($redirect_url);
			}

			$this->view->user_id = $resetting["user_id"];
			$this->view->guid = $resetting["guid"];
		}

		$this->view->errors = $this->_errorMessenger->getMessages();
		$this->_errorMessenger->clearMessages();

		$this->view->notifies = $this->_notifyMessenger->getMessages();
		$this->_notifyMessenger->clearMessages();
	}

	public function resetpostAction()
	{
		// check post method
		if(!$this->_request->isPost())
		{
			$redirect_url = $this->getUrl(array("module" => "cms", "controller" => "index", "action" => "index"));
			$this->_redirect($redirect_url);
		}

		// get params
		$password = $this->_request->getParam("password");
		$password2 = $this->_request->getParam("password2");
		$user_id = $this->_request->getParam("user_id");
		$guid = $this->_request->getParam("guid");

		// password & repassword aren't match
		if($password != $password2)
		{
			$this->_errorMessenger->addMessage("Xác nhận mật khẩu không đúng");
			$this->_redirect("user/account/reset");
		}

		// delete resetting record
		$resettingModel = $this->loadModel("user", "Resetting");
		$resettingModel->removeResettingByUserId($user_id);

		// change password
		$userModel = $this->loadModel("user", "Account");
		$userModel->changePassword($user_id, md5($password));

		$this->_notifyMessenger->addMessage("Đổi mật khẩu thành công");

		$this->_redirect("user/account/reset");
	}

	public function editAction()
	{
		$auth = Zend_Auth::getInstance();
		if($auth->hasIdentity())
		{
			$this->view->rightModules('right');
			$model = $this->loadModel('user', 'Account');
			$currentUser = $auth->getIdentity();
			$this->view->user = $model->getUserByUsername($currentUser->username);

			$this->view->errors = $this->_errorMessenger->getMessages();
			$this->_errorMessenger->clearMessages();

			$this->view->notifies = $this->_notifyMessenger->getMessages();
			$this->_notifyMessenger->clearMessages();
		}
		else
		{
			$redirect_url = $this->getUrl(array("module" => "user", "controller" => "account", "action" => "login"));
			$this->_redirect($redirect_url);
		}
	}

	public function editpostAction()
	{
		$auth = Zend_Auth::getInstance();
		if($auth->hasIdentity())
		{
			if($this->_request->isPost())
			{
				$currentUser = $this->auth->getIdentity();
				$model = $this->loadModel('user', 'Account');
				$user = $model->getUserByUsername($currentUser->username);
				$fullname = $this->_request->getParam('fullname');
				if(!is_null($fullname))
				{
					$user->fullname = $fullname;
					$currentUser->fullname = $fullname;
					$user->save();

					$this->_notifyMessenger->addMessage("Tài khoản cập nhật thành công!");

					$redirect_url = $this->getUrl(array("module" => "user", "controller" => "account", "action" => "edit"));
					$this->_redirect($redirect_url);
				}
				else
				{
					$this->_errorMessenger->addMessage("Tên đầy đủ không được rỗng");
				}
			}
		}
		else
		{
			$redirect_url = $this->getUrl(array("module" => "user", "controller" => "account", "action" => "login"));
			$this->_redirect($redirect_url);
		}
	}

	public function changepasswordAction()
	{
		$auth = Zend_Auth::getInstance();
		if($auth->hasIdentity())
		{
			$this->view->rightModules('right');
			$this->view->user = $auth->getIdentity();

			$this->view->errors = $this->_errorMessenger->getMessages();
			$this->_errorMessenger->clearMessages();

			$this->view->notifies = $this->_notifyMessenger->getMessages();
			$this->_notifyMessenger->clearMessages();
		}
		else
		{
			$redirect_url = $this->getUrl(array("module" => "user", "controller" => "account", "action" => "login"));
			$this->_redirect($redirect_url);
		}
	}

	public function changepasspostAction()
	{
		$error = false;
		if(!$this->auth->hasIdentity())
		{
			$redirect_url = $this->getUrl(array("module" => "user", "controller" => "account", "action" => "login"));
			$this->_redirect($redirect_url);
		}
		if($this->_request->isPost())
		{
			$model = $this->loadModel('user', 'Account');
			$password = $this->_request->getParam('password');
			$password2 = $this->_request->getParam('password2');
			$password3 = $this->_request->getParam('password3');
			if($this->_request->getParam('submit'))
			{
				if(!$password)
				{
					$error = true;
					$this->_errorMessenger->addMessage("Nhập mật khẩu mới");
				}
				else
				{

					if(!$password2)
					{
						$error = true;
						$this->_errorMessenger->addMessage("Nhập mật khẩu mới");
					}
					else if(!$password3)
					{
						$error = true;
						$this->_errorMessenger->addMessage("Nhập xác nhận mật khẩu");
					}
					else if($password2 != $password3)
					{
						$error = true;
						$this->_errorMessenger->addMessage("Xác nhận không đúng");
					}
					else
					{
						$user = $model->getUserByUsername($this->auth->getIdentity()->username);

						if($user->password != md5($password))
						{
							$error = true;
							$this->_errorMessenger->addMessage("Sai mật khẩu");
						}
					}
				}
			}
			if($error)
			{
				$redirect_url = $this->getUrl(array("module" => "user", "controller" => "account", "action" => "changepassword"));
				$this->_redirect($redirect_url);
			}
			else
			{
				$user = $model->getUserByUsername($this->auth->getIdentity()->username);
				$user->password = md5($password2);
				$user->save();

				$this->_notifyMessenger->addMessage("Mật khẩu thay đổi thành công!");

				$redirect_url = $this->getUrl(array("module" => "user", "controller" => "index", "action" => "index"));
				$this->_redirect($redirect_url);
			}
		}
	}
	
	public function confirmAction()
	{
		$id = $this->_request->getParam("id");
		if($id == null)
		{
			$this->_redirect("cms");
		}
		
		$model = $this->loadModel("user", "Account");
		$user = $model->getUserById($id);
		$user->active = 1;
		$user->save();
		
		$data = array(
			'subject' => "Chào mừng {$user->username} đến với HỘP MUA",
			'fmail' => 'info@hopmua.com',
			'fname' => 'admin',
			'tmail' => $user->email,
			'tname' => $user->username
		);
		$content = array("username" => $user->username);
		$this->sendmail($data, '', 'register.html', $content);
	}
}
?>
